package csvutils

import (
	"encoding/csv"
	"os"
)

type CsvFile struct {
	File   *os.File
	Writer *csv.Writer
}

func Open(path string) (*CsvFile, error) {
	file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		return nil, err
	}
	return &CsvFile{
		File:   file,
		Writer: csv.NewWriter(file),
	}, nil
}

func (cf *CsvFile) Write(record []string) error {
	cf.Writer.Write(record)
	cf.Writer.Flush()
	return cf.Writer.Error()

}

func (cf *CsvFile) Close() error {
	cf.Writer.Flush()
	return cf.File.Close()
}
